package com.cxt.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cxt.entity.CarpoolInfo;
import com.cxt.entity.WaypointInfo;
import com.cxt.service.ICarpoolInfoService;
import com.cxt.service.IMessageNotificationService;
import com.cxt.service.IWaypointInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class CarpoolInfoDataTask {
    @Autowired
    private ICarpoolInfoService carpoolInfoService;
    @Autowired
    private IWaypointInfoService waypointInfoService;
    @Autowired
    private IMessageNotificationService message;

    //首次执行一次，之后每隔10分钟执行一次，使用cron表达式
    //10秒执行一次
    @Scheduled(cron = "0/5 * * * * ?")
    @Scheduled(cron = "0 0/10 * * * ?")
    //事务管理
    @Transactional
    public void CarpoolData() {
        //获取前20分钟的未开始的拼车
        LambdaQueryWrapper<CarpoolInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CarpoolInfo::getCarpoolStatus, 1);
        wrapper.le(CarpoolInfo::getPlannedStartTime, LocalDateTime.now().minusMinutes(20));
        List<CarpoolInfo> carpoolInfos = carpoolInfoService.list(wrapper);
        //遍历这些拼车
        for (CarpoolInfo carpoolInfo : carpoolInfos) {
            log.info("拼车信息表：{}", carpoolInfo);
            //获取途径点
            List<WaypointInfo> waypointInfoList = waypointInfoService.getWaypointInfoByCarpoolId(carpoolInfo.getId());
            for (WaypointInfo waypointInfo : waypointInfoList) {
                if (waypointInfo.getWaypointType()!=1){
                    message.addMassage(waypointInfo.getUserId(),"您参与的拼车因人数不足未能成功，拼车已取消");
            }//删除途径点
                waypointInfoService.removeById(waypointInfo.getId());}
            //通知司机
            message.addMassage(carpoolInfo.getDriverId(),"您发布的拼车因人数不足未能成功，拼车已取消");
            carpoolInfoService.removeById(carpoolInfo.getId());
        }
    }
}
